#!/usr/bin/env python
# -*- coding: utf-8 -*-
# Author: zhengpingping

import sys
import xlrd3
import json

import operator
import importlib
import ExcelRead
importlib.reload(sys)

outPath = 'Json/'
#内部使用
search_names = []

#获取表格写入值
def get_write_value(value, typeRow):
    if typeRow == 'int':
        if(not value): value = 0
        value = str(value)
    elif typeRow == 'bool':
        if(not value): value = 0
        value = 'true' if value > 0 else 'false'
    elif typeRow == 'array_int':
        value = ("{@value}").replace("@value", str(value))
    else:
        value = ('@value').replace("@value", str(value))
    return value

#生成json
def create_json_file(ws):
    search_line = ExcelRead.excel_sheet_read(ws)
    field_keys = []; string = ''
    
        #生成数据
    for i in range(4, ws.nrows):
        readLine = {}

        for j in range(len(search_line)):
            line = search_line[j]
            
            cell_value = ExcelRead.get_cell_value(ws, i, line.fieldIdx)
            if(not ExcelRead.valid_check_value(cell_value, line.fieldType)):
                logStr = "{0}=={1}=={2} type is invalid"
                print(logStr.format(line.fieldName, line.fieldIdx, cell_value))
                readLine = {}; break
            
            cell_value = get_write_value(cell_value, line.fieldType)
            if(j == 0):
                contain = operator.contains(field_keys, cell_value)
                if(contain):
                    print(ws.name + '--表格中key值重复:' + cell_value)
                    readLine = {}; break
                field_keys.append(cell_value)
            
            readLine[line.fieldName] = cell_value
        if(len(readLine) > 0):
            string += json.dumps(readLine, ensure_ascii = False) + ',\r\n'
    string = ("[\r\n@temp]").replace("@temp", string)

    search_names.append(ws.name)
    outputName = ("@Name.json").replace("@Name", ws.name)
    ExcelRead.save_file(outPath + outputName, string)

# 读取excel文件
def excel_sheet_read(file):
    wb = xlrd3.open_workbook(file)
    for sheet in wb.sheets():
        print(sheet.name + ' translate create')
        if(ExcelRead.check_fileName(sheet.name, search_names)):
            create_json_file(sheet)

# 初始化方法
ExcelRead.init(outPath, excel_sheet_read)